package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import Data.User;
import Data.UserManager;

/**
 * a servlet that is responsible for the authentication to the system
 * the servlet get a user first & last name and search if the user exist in DB
 * if yes he will be redirected to the page of the dropbox files 
 * if not he will get a false page saying the first or last name is incorrect 
 * Servlet implementation class AuthenticationServlet
 */

public class AuthenticationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthenticationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

    /**
     * using the post method, and getting the first and last name from the http request.
     * creating a session with the database and checking if they exist 
     * if so, then we create a page that redirects them to the dropbox page
     * else we send them to an "error page"
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String firstName = request.getParameter("firstName").toString();
        String lastName = request.getParameter("lastName").toString();
        User user ;
        //user.setFirstName("Kermit1");
        //user.setLastName("Frog");
        //user.setAge(54);
        //user.setEmail("kermit@muppets.com");

        //SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
        //Session session = sessionFactory.openSession();
        //UserManager manager = new UserManager(session);

        //manager.saveUser(user);
        //System.out.println("User saved with ID = "+ user.getUserId());

        //session.flush();
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();

    	Query query = session.createQuery("from User");
    	@SuppressWarnings("unchecked")
    	List<User> list = query.list();
    	Iterator<User> it=list.iterator();
    	int flag=0;
    	while (it.hasNext() && flag==0)
    	{
	    	  user=it.next();
	    	  if(user.getFirstName().equals(firstName)==true && user.getLastName().equals(lastName)==true)
	    	  {
		    		      
		    		  	  out.println("<html>");
				    	  out.println("<head>");
				    	  out.println("<title>DropBox Server</title>");
				    	  out.println("</head>");
				      	  out.println("<body>");
				    	  out.println("<p>welcome " + firstName + " " + lastName + " to the server main page.</p><br><br>");
				    	  
				    	  out.println("<script type=\"text/javascript\">");

				    	  out.println("function dodelay() {  "); 

				    	  out.println("window.location = \"files.jsp\"");

				    	  out.println("}");


				    	  out.println("</script>");

				    	  out.println("</head>");

				    	  out.println("<body onLoad=\"setTimeout('dodelay()', 5000)\">");

				      	  out.println("<p>");

				    	  out.println("You will be redirect to our new website in 5 seconds.");

				    	  out.println("Click <a href=\"files.jsp\">here</a> to go immediately.");

				    	  out.println("</p> ");
				    	  out.println("</body>");
				    	  out.println("</html>");
				    	  out.close();
				    	   //String redirectURL = "files.jsp";
				    	  //response.sendRedirect(redirectURL);
			    		 
			    		  	
			    		  flag=1;
		    		  
	    	  }
    	}
    	if(flag==0)
    	{
    		 /*
    		 out.println("<html>");
   		 	 out.println("<head>");
   		 	 out.println("<title>DropBox Server</title>");
	   		 out.println("</head>");
	   		 out.println("<body>");
	   		 out.println("<p>login failed to the server main page</p>");
	   		 out.println("</body>");
	   		 out.println("</html>");
	   		 */
    		 String redirectURL = "LoginFailed.html";
    	     response.sendRedirect(redirectURL);
    	}
    	session.flush();
	}
	

}
